package com.qzboot.basic.service.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.qzboot.common.util.SnowflakeIdUtil;
import com.qzboot.facade.common.MpSupport;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 自动为实体创建时间和更新时间赋值
 *
 * @author zengzhihong
 * @date 2019-04-17
 */
@Component
public class MybatisPlusMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        Long id = (Long) this.getFieldValByName(MpSupport.ID_COLUMN, metaObject);
        Date now = null == id ? new Date() : SnowflakeIdUtil.convertDate(id);
        //如果已对createTime赋值 则不处理
        this.setFieldValByName(MpSupport.CREATE_TIME_COLUMN, now, metaObject);
        this.setFieldValByName(MpSupport.UPDATE_TIME_COLUMN, now, metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.setFieldValByName(MpSupport.UPDATE_TIME_COLUMN, new Date(), metaObject);
    }
}
